import sys
import datetime
import os
import psutil
from PySide2.QtWidgets import (QApplication, QMainWindow, QFileDialog, 
                              QMessageBox, QListWidgetItem, QLabel)
from PySide2.QtCore import Qt, QThread, Signal, QPoint, QTimer
from PySide2.QtGui import QCursor, QIcon
from PySide2.QtGui import QIntValidator
import config_manager
from friend_addition import HumanizedFriendAdditionWorker
from log_config import setup_logging
from Ui_mainwindow import Ui_MainWindow
from vjiajia_utils.wechat_utils import get_wechat_version
# 初始化日志
logger = setup_logging()
logger.info("应用启动")

# 有效期设置
EXPIRY_DATE = datetime.datetime(2026, 3, 1)

if datetime.datetime.now() > EXPIRY_DATE:
    error_msg = "微加加 - 微信好友批量添加工具已过有效期，请联系相关人员获取新的授权。"
    print(error_msg)
    sys.exit(1)

class MainWindow(QMainWindow, Ui_MainWindow):
    def __init__(self):
        super().__init__()
        self.setupUi(self)
        
        # 初始化
        self.init_variables()
        self.init_ui()
        self.init_signal_slots()
        self.load_settings()

    def _main_log(self, message):
        self.show_log(message)
        print(message)
    def init_variables(self):
        """初始化变量"""
        self.is_maximized = False
        self.drag_start_pos = QPoint()
        self.is_dragging = False
        self.file_path_var = ""
        self.worker = None
        self.interval_seconds = 15
        self.remaining_seconds = 0
        self.total_records = 0
        self.processed_records = 0
        self.send_request_count = 0

    def init_ui(self):
        """初始化界面"""
        # 窗口设置
        self.setWindowFlags(Qt.FramelessWindowHint | Qt.WindowSystemMenuHint)
        self.setAttribute(Qt.WA_TranslucentBackground)
        
        # 初始化菜单列表
        self.init_menu_list()
        
        # 设置标题栏可拖拽
        self.frame_2.mousePressEvent = self.handle_mouse_press
        self.frame_2.mouseMoveEvent = self.handle_mouse_move
        self.frame_2.mouseReleaseEvent = self.handle_mouse_release

        self.lineEdit_target_num.setValidator(QIntValidator())
        self.lineEdit_time_interval.setValidator(QIntValidator())
        # 初始化状态标签
        self.label_status.setText("准备就绪")
        self.label_status.setStyleSheet("font-weight: bold;")

    def init_menu_list(self):
        """初始化左侧菜单列表"""
        menu_items = [
            {"text": "批量添加好友", "icon": ":/icons/icons/add_friend.png"},
            {"text": "设置", "icon": ":/icons/icons/settings.png"},
            {"text": "使用帮助", "icon": ":/icons/icons/help.png"},
            {"text": "关于我们", "icon": ":/icons/icons/about.png"}
        ]
        
        for item in menu_items:
            list_item = QListWidgetItem(QIcon(item["icon"]), item["text"])
            list_item.setData(Qt.UserRole, item["text"])
            self.list_menu.addItem(list_item)
        
        self.list_menu.setCurrentRow(0)

    def init_signal_slots(self):
        """初始化信号槽连接"""
        # 窗口控制按钮
        self.button_minimize.clicked.connect(self.showMinimized)
        self.button_close.clicked.connect(self.close)
        
        # 功能按钮
        self.button_file_select.clicked.connect(self.select_file)
        self.button_start_stop.clicked.connect(self.start_stop_process)
        
        # 菜单项点击
        self.list_menu.itemClicked.connect(self.on_menu_item_clicked)

    def handle_mouse_press(self, event):
        """鼠标按下事件 - 开始拖拽"""
        if event.button() == Qt.LeftButton:
            self.drag_start_pos = event.globalPos()
            self.is_dragging = True
            self.setCursor(QCursor(Qt.OpenHandCursor))
            event.accept()

    def handle_mouse_move(self, event):
        """鼠标移动事件 - 拖拽窗口"""
        if self.is_dragging and event.buttons() & Qt.LeftButton:
            move_pos = event.globalPos() - self.drag_start_pos
            self.move(self.pos() + move_pos)
            self.drag_start_pos = event.globalPos()
            self.setCursor(QCursor(Qt.ClosedHandCursor))
            event.accept()

    def handle_mouse_release(self, event):
        """鼠标释放事件 - 结束拖拽"""
        self.is_dragging = False
        self.setCursor(QCursor(Qt.ArrowCursor))
        event.accept()

    def on_menu_item_clicked(self, item):
        """菜单项点击事件处理"""
        menu_text = item.data(Qt.UserRole)
        logger.info(f"菜单项点击: {menu_text}")
        
        if menu_text == "批量添加好友":
            pass  # 已经是当前页面
        elif menu_text == "设置":
            QMessageBox.information(self, "提示", "设置功能正在开发中")
        elif menu_text == "使用帮助":
            QMessageBox.information(self, "提示", "使用帮助正在开发中")
        elif menu_text == "关于我们":
            QMessageBox.information(self, "关于", 
                                  "微加加 - 微信好友批量添加工具\n版本: 1.0.0\n© 2023")

    def load_settings(self):
        """加载保存的设置"""
        config = config_manager.load_config()
        if config:
            self.lineEdit_apply_msg.setText(config.get("apply_msg", ""))
            self.lineEdit_prefix.setText(config.get("prefix", ""))
            self.lineEdit_tag.setText(config.get("tag", ""))
            self.lineEdit_time_interval.setText(str(config.get("interval_time", 15)))
            self.lineEdit_target_num.setText(str(config.get("target_num", 20)))
            self.file_path_var = config.get("file_path", "")
            self.label_file_path.setText(self.file_path_var if self.file_path_var else "未选择文件")
            self.checkBox_remember.setChecked(config.get("remember", False))
        else:
            self.lineEdit_apply_msg.setText("您好，我是XXX，想加您好友，您是 {name} 吧？")
            self.lineEdit_prefix.setText("21届土木工程")
            self.lineEdit_time_interval.setText(str(120))
            self.lineEdit_target_num.setText(str(20))
            self.label_file_path.setText("未选择文件")
            self.checkBox_remember.setChecked(False) 

    def select_file(self):
        """选择Excel文件"""
        file_path, _ = QFileDialog.getOpenFileName(
            self, "选择 Excel 文件", "", "Excel files (*.xlsx *.xls)"
        )
        if file_path:
            self.file_path_var = file_path
            self.label_file_path.setText(file_path)
            
            # 自动填充前缀（如果为空）
            if not self.lineEdit_prefix.text():
                filename = os.path.splitext(os.path.basename(file_path))[0]
                self.lineEdit_prefix.setText(filename)

    def start_stop_process(self):
        """开始处理任务"""
        # 任务在跑就结束
        if hasattr(self, 'worker') and self.worker and self.worker.isRunning():
            self.worker.stop()
            self.button_start_stop.setText("正在结束...")
            self.button_start_stop.setEnabled(False)
            return
        

        apply_msg = self.lineEdit_apply_msg.text()
        # 备注前缀输入框没填时，赋值一个空白字符
        prefix = self.lineEdit_prefix.text() or ""
        tag = self.lineEdit_tag.text() or ""
        target_num = int(self.lineEdit_target_num.text())
        file_path = self.file_path_var
        
        try:
            self.interval_seconds = int(self.lineEdit_time_interval.text())
            if self.interval_seconds < 5:
                QMessageBox.warning(self, "提示", "间隔时间应大于5秒")
                return
        except ValueError:
            QMessageBox.warning(self, "提示", "请输入有效的间隔时间")
            return
        
        if not apply_msg:
            QMessageBox.warning(self, "提示", "请输入申请好友信息！")
            return
        
        if not target_num:
            QMessageBox.warning(self, "提示", "请输入目标添加好友数！")
            return
            
        # if not prefix:
        #     QMessageBox.warning(self, "提示", "请输入备注前缀！")
        #     return
            
        if not file_path or not os.path.exists(file_path):
            QMessageBox.warning(self, "提示", "请选择有效的Excel文件！")
            return
        
                # 更新按钮状态
        self.button_start_stop.setText("强制结束")
        self.button_start_stop.setProperty("running", True)
        self.button_start_stop.style().polish(self.button_start_stop)  # 强制刷新样式

        # 保存设置
        if self.checkBox_remember.isChecked():
            config_manager.save_config(
                apply_msg, 
                prefix, 
                file_path, 
                True,
                self.interval_seconds,
                target_num,
                tag=tag
            )
        
        logger.info(f"开始处理添加好友任务，间隔时间: {self.interval_seconds}秒")
        
        self.label_countdown.setText("正在添加...")
        self.label_status.setText("正在初始化...")

        # 创建并启动工作线程
        self.worker = HumanizedFriendAdditionWorker(
            file_path, 
            apply_msg, 
            prefix,
            self.interval_seconds,
            target_num,
            tag
        )
        self.worker.interval_remaining_signal.connect(self.update_interval_remaining)
        self.worker.progress_signal.connect(self.update_progress)
        self.worker.finished_signal.connect(self.on_process_finished)
        self.worker.error_signal.connect(self.show_error)
        self.worker.log_signal.connect(self.show_log)
        self.worker.force_stop_signal.connect(self.force_stop)
        self.worker.start()

    def update_interval_remaining(self, remaining):
        # 更新倒计时显示
        self.remaining_seconds = remaining
        if self.remaining_seconds > 0:
            mins = self.remaining_seconds // 60
            secs = self.remaining_seconds % 60
            self.label_countdown.setText(f"下一个添加: {mins:02d}:{secs:02d}")
            self.remaining_seconds -= 1
        else:
            self.label_countdown.setText("正在添加...")
        
    def update_progress(self, total, processed, send_request_count):
        """更新进度"""
        # 保存进度数据
        self.total_records = total
        self.processed_records = processed
        self.send_request_count = send_request_count
        
        # 更新状态标签
        status_text = f"文件行数: {total} | 已处理: {processed} | 发送请求: {send_request_count}/{self.lineEdit_target_num.text() or '∞'}"
        self.label_status.setText(status_text)


    def show_error(self, error_msg):
        """显示错误信息"""
        QMessageBox.critical(self, "错误", error_msg)
        #self.on_process_finished()

    def show_log(self, log_msg):
        self.textEdit_log.appendPlainText(log_msg)
        self.textEdit_log.verticalScrollBar().setValue(self.textEdit_log.verticalScrollBar().maximum())

    def force_stop(self):
        self.button_start_stop.setProperty("running", False)
        self.button_start_stop.style().polish(self.button_start_stop)
        self.button_start_stop.setEnabled(True)
        self.label_status.setText("已强制停止")
        QMessageBox.information(self, "提示", "停止好友添加请求！新文件已保存。")

    def on_process_finished(self, status):
        """处理完成"""
        self.show_log(f"on_process_finished， status ={status}")
        self.button_start_stop.setText("开始")
        self.button_start_stop.setProperty("running", False)
        self.button_start_stop.style().polish(self.button_start_stop)
        self.button_start_stop.setEnabled(True)

        self.statusBar().showMessage("所有好友添加请求已发送完毕！", 5000)
        self.label_countdown.setText("任务完成")
        
        # 更新最终状态
        status_text = f"任务完成 | 总处理: {self.processed_records}/{self.total_records} | 发送请求: {self.send_request_count}"
        if status == "completed":
            QMessageBox.information(self, "提示", "所有好友添加请求已发送完毕！新文件已保存。")
        elif status == "rate_limited":
            QMessageBox.warning(self, "警告", "微信操作频繁限制已触发，请等待24小时后继续")

    def closeEvent(self, event):
        """关闭事件处理"""
        if hasattr(self, 'worker') and self.worker and self.worker.isRunning():
            reply = QMessageBox.question(
                self, '确认', 
                '处理任务正在进行中，确定要退出吗？', 
                QMessageBox.Yes | QMessageBox.No, 
                QMessageBox.No
            )
            
            if reply == QMessageBox.No:
                event.ignore()
                return
            else:
                try:
                    self.worker.stop()
                    current_pid = os.getpid()
                    parent = psutil.Process(current_pid)
                    for child in parent.children(recursive=True):
                        child.terminate()
                    parent.terminate()
                    parent.wait()
                except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
                    pass
        
        # 保存当前设置
        if self.checkBox_remember.isChecked():
            config_manager.save_config(
                self.lineEdit_apply_msg.text(),
                self.lineEdit_prefix.text(),
                self.file_path_var,
                True,
                self.interval_seconds,
                self.lineEdit_target_num.text(),
                self.lineEdit_tag.text()
            )
        
        event.accept()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    
    # 创建并显示主窗口
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())